/*
 * Copyright 2015 LinkedIn Corp. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 */

package com.linkedin.paldb.impl;

import com.linkedin.paldb.api.Configuration;
import com.linkedin.paldb.api.StoreWriter;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Store writer implementation.
 * 主要是负责构建write过程重要的组件：
 * 1） StorageWriter：负责写入
 * 2）StorageSerialization：负责序列化，key-value都将被序列化
 */
public final class WriterImpl implements StoreWriter {

    // Logger
    private final static Logger LOGGER = Logger.getLogger(WriterImpl.class.getName());
    // Configuration
    /**
     * 包含全局配置类
     */
    private final Configuration config;
    // Storage
    /**
     * 写数据的主要实现类
     */
    private final StorageWriter storage;
    // Serialization
    /**
     * 序列化的实现
     */
    private final StorageSerialization serialization;
    // File (can be null)
    /**
     * 没有实际作用，只用来打印日志
     */
    private final File file;
    // Stream
    /**
     * 最终统一输出到该文件流
     */
    private final OutputStream outputStream;
    // Opened?
    /**
     * 构建完成后，在调用close方法之前为true
     */
    private boolean opened;

    /**
     * File constructor.
     *
     * @param config configuration
     * @param file input file
     */
    WriterImpl(Configuration config, File file)
            throws IOException {
        this(config, new FileOutputStream(file), file);
    }

    /**
     * Stream constructor.
     *
     * @param config configuration
     * @param stream input stream
     */
    WriterImpl(Configuration config, OutputStream stream) {
        this(config, stream, null);
    }

    /**
     * Private constructor.
     *
     * @param config configuration
     * @param stream output stream
     */
    private WriterImpl(Configuration config, OutputStream stream, File file) {
        this.config = config;
        this.outputStream = stream;
        this.file = file;

        // Open storage
        LOGGER.log(Level.INFO, "Opening writer storage");
        // 根据配置狗i教案序列化实现
        serialization = new StorageSerialization(config);
        // 构建存储写入实现
        storage = new StorageWriter(config, outputStream);
        // flag：表示writer启用
        opened = true;
    }

    @Override
    public void close() {
        checkOpen();
        try {
            if (file != null) {
                LOGGER.log(Level.INFO, "Closing writer storage, writing to file at " + file.getAbsolutePath());
            } else {
                LOGGER.log(Level.INFO, "Closing writer storage, writing to stream");
            }
            // 先关闭存储，合并临时文件到DB文件，之所以在close的时候合并，是因为put操作不知道什么时候结束
            storage.close();
            // 再关闭写文件的流
            outputStream.close();
            opened = false;
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        }
    }

    @Override
    public Configuration getConfiguration() {
        return config;
    }

    @Override
    public void put(Object key, Object value) {
        checkOpen();
        if (key == null) {
            throw new NullPointerException();
        }
        try {
            byte[] keyBytes = serialization.serializeKey(key);
            storage.put(keyBytes, serialization.serializeValue(value));
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        }
    }

    @Override
    public void putAll(Object[] keys, Object[] values) {
        checkOpen();
        if (keys == null || values == null) {
            throw new NullPointerException();
        }
        if (keys.length != values.length) {
            throw new IllegalArgumentException("Key and value collections should be the same size");
        }
        int size = keys.length;
        for (int i = 0; i < size; i++) {
            put(keys[i], values[i]);
        }
    }

    @Override
    public void put(byte[] key, byte[] value) {
        checkOpen();
        if (key == null || value == null) {
            throw new NullPointerException();
        }
        try {
            storage.put(key, value);
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        }
    }

    // UTILITIES

    private void checkOpen() {
        if (!opened) {
            throw new IllegalStateException("The store is closed");
        }
    }
}
